/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2022-01-09 19:06:17
 */
import { IAllObject } from "@/types/base";
import React, { memo, useEffect, useState } from "react";
import "./style.scss";

interface IsvgIconProps extends IAllObject {
  name: string;
  size?: number;
  fill?: string;
  className?: string;
  diyStyle?: React.CSSProperties;
  hover?: boolean;
  click?: () => void
}

const defaultProps = {
  size: 16,
  fill: "currentColor",
  className: "",
  hover: false,
};

const svgIcon: React.FC<IsvgIconProps> = memo((props) => {
  
  const { name, className, diyStyle, hover, size, fill, click } = props;
  const [symbolId, setSymbolId] = useState(`#icon-${name}`),
        [svgClass, setSvgClass] = useState(`svg-icon ${className}`),
        [style, setStyle] = useState({})
  useEffect(() => {
    const getStyle = () => {
      let s = `${size}`;
      s = `${s.replace('px', '')}px`;
      const res = {
        width: s,
        height: s,
        fill,
    }
      if(diyStyle) return Object.assign(diyStyle, res);
      return res
    }
    setSymbolId(`#icon-${name}`);
    hover && setSvgClass(`svg-icon ${className} hoverd`);
    setStyle(getStyle())
  }, [name, className]);
  return (
    <svg className={svgClass} style={style} aria-hidden="true" onClick={() => click && click()}>
      <use className="use" href={symbolId} />
    </svg>
  );
});

svgIcon.defaultProps = defaultProps;

export default svgIcon;
